﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;

namespace SoundServant
{
    static public class Logs
    {
        private static StreamWriter logFile;

        public delegate void NewMessageEventHandler(LogMessage logMessage);
        public static event NewMessageEventHandler NewMessage;

        static Logs()
        {
            DateTime logFileDate = DateTime.Now;
            string logFileName = Options.Default.BaseDirectory + "\\" + Options.Default.LogDirectory + "\\" + logFileDate.Ticks + ".txt";
            if (File.Exists(logFileName)) File.Delete(logFileName);
            logFile = new StreamWriter(new FileStream(logFileName, FileMode.Create));

            logFile.WriteLine("SOUND SERVANT " + SS.Version());
            logFile.Flush();

        }

        public static void Information(string title, string message)
        {
            LogMessage logMessage = new LogMessage(title, message);
            WriteToLog(logMessage);
            if (NewMessage != null)
                NewMessage(logMessage);
        }

        public static void UserPrompt(string title, string message)
        {

        }

        public static void FatalError(string title, string message)
        {

        }

        public static void Error(string title, string message, string exceptionMessage)
        {
            LogMessage logMessage = new LogMessage(title, message, exceptionMessage);
            SSMessageBox.Show(title, message + "\r\n\r\n" + exceptionMessage, SSMessageBoxType.Ok);
            WriteToLog(logMessage);
            if (NewMessage != null) NewMessage(logMessage);
        }

        private static void WriteToLog(LogMessage logMessage)
        {
            string textToWrite = logMessage.Time.ToString("dd.MM.yy HH:mm:ss") + " [" + logMessage.Title + "] " + logMessage.Message;
            if (logMessage.ExceptionMessage != null)
            {
                textToWrite += "\r\n\r\n" + logMessage.ExceptionMessage + "\r\n\r\n";
            }
            logFile.WriteLine(textToWrite);
            logFile.Flush();
        }
    }

    public class LogMessage
    {
        public readonly string Title;
        public readonly string Message;
        public readonly DateTime Time;
        public readonly string ExceptionMessage;

        public LogMessage(string title, string message, string exceptionMessage)
        {
            Title = title.ToUpper();
            Message = message;
            Time = DateTime.Now;
            ExceptionMessage = exceptionMessage;
        }

        public LogMessage(string title, string message)
        {
            Title = title.ToUpper();
            Message = message;
            Time = DateTime.Now;
            ExceptionMessage = null;
        }
    }

    public enum MessageType
    {
        Information,
        Important,
        UserPrompt,
        Error,
        FatalError
    }
}
